<?php

namespace Yjius\openapi\dingtalk;

use Yjius\common\CurlHelper;

/**
 * 钉钉扫码登录
 * Class DingTalkOAuth
 * @package Yjius\oauthird
 * @date  2022/7/26 14:23
 */
class DingTalkOAuth
{
    protected $clientId = "";
    protected $clientSecret = "";

    public function __construct($config = [])
    {
        if (!empty($config['app_key'])) {
            $this->clientId = $config['app_key'];
        }
        if (!empty($config['app_secret'])) {
            $this->clientSecret = $config['app_secret'];
        }
        if (empty($this->clientId) || empty($this->clientSecret)) {
            throw new \Exception("请联系相关人员获取合法的api_secret");
        }
    }

    //钉钉文档
    //https://open.dingtalk.com/document/orgapp-server/tutorial-obtaining-user-personal-information
    // 1.生成链接登录链接，跳转
    // 2.设置钉钉应用里的登录与分享回调地址
    // 3.接收回调，处理信息获取用于唯一ID
    public function getCodeUrl($redirect_uri, $state = '')
    {
        $url = "https://login.dingtalk.com/oauth2/auth?redirect_uri=" . urlencode($redirect_uri) .
            "&response_type=code&client_id=ding2ygycowxy0uryesp&scope=openid&state=" . $state . "&prompt=consent";
        return $url;
    }

    //第二步
    public function getAccessToken($authCode)
    {
        $data = [
            'clientId' => $this->clientId,
            'clientSecret' => $this->clientSecret,
            'code' => $authCode,
            'refreshToken' => '',
            'grantType' => 'authorization_code'
        ];
        $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
        $headers = ['Content-Type: application/json', 'Content-Length: ' . strlen($jsonData)];
        $accessToken = CurlHelper::httpRequest("https://api.dingtalk.com/v1.0/oauth2/userAccessToken", $headers, 'POST', [], $jsonData);
        $accessToken = json_decode($accessToken, true);
        return $accessToken;
    }

    /**
     * 第三步：获取登录用户信息
     */
    public function getLoginInfo($accessToken = [])
    {
        $headers = ["Content-Type: application/json", "x-acs-dingtalk-access-token: {$accessToken['accessToken']}"];
        $userRes = CurlHelper::httpRequest("https://api.dingtalk.com/v1.0/contact/users/me", $headers, 'GET', []);
        $userRes = json_decode($userRes, true);
        return $userRes;
    }

}